Ext.Loader.setPath("FormFieldUtil",contextPath+"ui_tpl/FormFieldUtil.js");
Ext.define('Ext.ux.SearchEditGrid',{
		extend:"Ext.container.Container",
		xtype:"searcheditgrid",
		layout:"border",
		requires: [
		        'Ext.toolbar.Paging',
		        'FormFieldUtil'
		],
		initComponent:function(){
			var me=this,metaData=this.metaData,
			mainMetaId=this.mainMetaId,
			globalId=this.globalId,
			refMetaMap=this.refMetaMap=metaData["refMetaMap"],
			mainMeta=this.mainMeta=refMetaMap[mainMetaId],
			protoMetaId=mainMeta["meta"],
			protoMeta=refMetaMap[protoMetaId],
			fields=this.fields=mainMeta["fields"],
			attrs=this.attrs=mainMeta["attrs"],
			action=me.action=attrs['action']||{type:"rest",url:"/meta/record/"+mainMetaId},
			modelName=me.modelName="App.data."+mainMeta["code"],
			modelFields=[],columns=[],validators={};
			me.gridId="grid_"+mainMetaId+"_"+globalId;
			me.pagingtoolbarId="pageTool_"+mainMetaId+"_"+globalId;
			if(globalId&&globalId>0){
				me.modelName+=globalId;
			}
			Ext.apply(this,attrs);
			this.searchFields=attrs["searchFields"]||['name','text'];
			this.showColumns=attrs["showColumns"];
			var searchForm=this.searchForm=this.initSearchForm('north'),
			dataGrid=this.dataGrid=this.initDataGrid('center');
			this.items=[searchForm,dataGrid];
			this.callParent();
		},
		initGridModel:function(){
			var me=this,attrs=me['attrs'], fields=me.fields,typeMap=me["typeMap"],
			modelFields=this.modelFields=[],columns=this.columns=[],
			parentIdProperty=attrs["parentIdProperty"]||"fid";
			Ext.iterate(fields,function(field,i){
				
				var type=field["type"],name=field["name"],f={name:name,type:typeMap[field["type"]]},
				attrs=field["attrs"],
				col={dataIndex:name,text:field["text"],menuDisabled:true},
				valid={};
				if(attrs["enums"]){
					col["renderer"]=(function(){
						var enums=attrs["enums"],vf=attrs["valueField"]||"code",df=attrs["displayField"]||"text";
						enums=enums.substring(enums.indexOf("$")+1);
						var enumData=refEnumMap[enums],remap={};
						var list=enumData["list"];
						Ext.iterate(list,function(n,i){
							remap[n[vf]]=n[df];
						});
						switch(type){
							case -5:
							case 4:
								return function(v){
									return remap[v+""];
								};
								break;
							default :
								return function(v){
									return remap[v];
								}
						}
					})();
				}else{
					switch(type){
					case -5:
					case 4:
						break;
					case 91:
						col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d');
						break;
					case 92:
						col["renderer"]=Ext.util.Format.dateRenderer('h:i:s');
						break;
					case 93:
						col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d h:i:s');
						col["width"]=150;
						break;
					}
				}
				
				modelFields.push(f);
				columns.push(col);
			});
			if(!Ext.ClassManager.isCreated(me.modelName)){
				var startParam ="pageInfo.start",limitParam="pageInfo.limit",pageParam="pageInfo.page",
				sortParam="sortInfo.field",directionParam="sortInfo.direct",
				paramNames={
						startParam:startParam,
						limitParam:limitParam,
						pageParam:pageParam,
						sortParam:sortParam,
						directionParam:directionParam
						},extraParams={};
				if(me["seqProperty"]&&me.globalId){
					extraParams[sortParam]=me["seqProperty"];
					extraParams[directionParam]="ASC";
				}else{
					extraParams[sortParam]=(attrs.idProperty||"id");
					extraParams[directionParam]="ASC";
				}
				
				if(globalId&&globalId>0){
					extraParams["filter."+parentIdProperty]=globalId;
				}
				var action=this["action"];
				var proxy={
						url:action["url"],
						type:action["type"],
						extraParams: extraParams,
						reader: {  
			                type: 'json',
			                rootProperty: 'itemList',
			                totalProperty: 'pageInfo.total'
			            },
			            simpleSortMode: true
					};
				Ext.apply(proxy,paramNames);
				Ext.define(me.modelName,{
					extend:"Ext.data.Model",
					idProperty:attrs["idProperty"]||"id",
					fields:modelFields,
					proxy:proxy
				});
			}
		},
		initGridStore:function(){
			this.initGridModel();
			var me=this,sorters=[],store=this.store=Ext.create('Ext.data.Store',{
				model:me.modelName,
				autoLoad:true,
				sorters:sorters
			});
			if(me["seqProperty"]){
				sorters.push({
					property:me["seqProperty"],
					direction:"asc"
				});
			}else{
				sorters.push({
					property:me["idProperty"],
					direction:"asc"
				});
			}
			return store;
		},
		initTBar:function(){
			var me=this,
			tbar=this.tbar=[{
				text:"新增",
				iconCls:"fa fa-plus",
				handler:function(){
					me.showAddWin();
				}
			},{
				text:"编辑",
				iconCls:"fa fa-edit",
				handler:function(){
					me.showEditWin();
				}
			},{
				text:"刷新",
				iconCls:"fa fa-refresh",
				handler:function(){
					me.refreshGrid();
				}
			},{
				text:"查看",
				iconCls:"fa fa-eye",
				handler:function(){
					me.showViewWin();
				}
			},{
				text:"删除",
				iconCls:"fa fa-remove",
				handler:function(){
					var grid=me.getComponent(me.gridId),sels=grid.getSelection();
					if(sels.length==0)return Ext.toast('提示','请先选择要删除的记录');
					Ext.Msg.confirm('确认','确定要删除选定的记录吗?',function(btn){
						if(btn=='no')return ;
						Ext.iterate(sels,function(sel,i){
							sel.erase({
								callback:function(){
									me.refreshGrid();
								}
							});
						});
					})
					
				}
			}];
			if(me["seqProperty"]){
				this.moveUrl=contextPath+"meta/record/offset/"+me.mainMetaId;
				tbar.push({
					text:"上移",
					iconCls:"fa fa-arrow-up",
					handler:function(){
						var sels=me.getComponent(me.gridId).getSelection();
						if(sels.length==0)return;
						var sel=sels[0];
						Ext.Ajax.request({
							url:me.moveUrl,
							params:{
								id:sel.get(me.idProperty),
								step:-1
							},
							success:function(){
								me.refreshGrid();
							},
							failure:function(){
								me.refreshGrid();
							}
						});
						
					}
				});
				tbar.push({
					text:"下移",
					iconCls:"fa fa-arrow-down",
					handler:function(){
						var sels=me.getComponent(me.gridId).getSelection();
						if(sels.length==0)return;
						var sel=sels[0];
						Ext.Ajax.request({
							url:me.moveUrl,
							params:{
								id:sel.get(me.idProperty),
								step:1
							},
							success:function(){
								me.refreshGrid();
							},
							failure:function(){
								me.refreshGrid();
							}
						});
					}
				});
			}
		},
		typeMap:{"1":"string","-5":"int","4":"int","12":"string","16":"boolean",
			"91":"date","93":"date","97":"date"},
		
		showViewWin:function(){
			var me=this,grid=me.getComponent(me.gridId),sels=grid.getSelection();
			if(sels.length==0)return Ext.toast('请选择要查看的记录','提示');
			var sel=sels[0],name="viewWin"+me["mainMetaId"],
			win=me.getComponent(name);
			if(!win){
				win=Ext.create({
					xtype:"form",
					itemId:name,
					bodyPadding:"10 10 10 0",
					defaults:{
						xtype:"textfield",
						width:300,
						readOnly:true
					},
					items:FormFieldUtil.getFormFields(me["mainMetaId"],me.metaData),
					floating:true,
					draggable:true,
					modal:true,
					title:"查看",
					width:350,
					height:400,
					scrollable:true,
					closable:true
					
				});
			}
			win.loadRecord(sel);
			win.show();
		},
		showAddWin:function(){
			var me=this,metaData=this.metaData,
			mainMeta=this.mainMeta,moduleId=this.mainMetaId,attrs=mainMeta["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			winName=this.addNodeWinName="addNodeWin"+moduleId;
			var win=this.getComponent(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(moduleId,metaData);
				var action=this["action"];
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name==idProperty){
						item.value=-1;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}else if(name==me["parentIdProperty"]){
						item.readOnly=true;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"新增",
					itemId:winName,
					bodyPadding:"10 10 10 0",
					url:action["url"],
					closeToolText:"关闭",
					draggable:true,
					modal:true,
					closable:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:action["method"]||"PUT",
					items:items,
					buttons:[{
						text:'提交',
						iconCls:'fa fa-save',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("新增成功",'提示', 't');
					                    	me.refreshGrid();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshGrid();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						iconCls:"fa fa-remove",
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var form=win.getForm(),pfield=form.findField(me.parentIdProperty);
			pfield&&pfield.setValue(me.globalId);
			Ext.iterate(this.defaultValueMap,function(name,v){
				var f=form.findField(name);
				f&&f.setValue(v);
			});
			win.show();
			
		},
		showEditWin:function(){
			var me=this,metaData=this.metaData,action=this.action,
			mainMeta=this.mainMeta,moduleId=this.mainMetaId,attrs=mainMeta["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			grid=me.getComponent(me.gridId),sels=grid.getSelection();
			if(sels.length==0)return Ext.toast('请选择要编辑的记录','提示');
			var sel=sels[0],name="editWin_"+moduleId,
			win=this.getComponent(name);
			if(!win){
				win=Ext.create({
					xtype:"form",
					itemId:name,
					modal:true,
					bodyPadding:"10 10 10 0",
					defaults:{
						xtype:"textfield",
						width:300
					},
					url:action["url"],
					method:action["method"]||"POST",
					items:FormFieldUtil.getFormFields(moduleId,metaData),
					floating:true,
					draggable:true,
					title:"编辑",
					width:350,
					height:400,
					scrollable:true,
					closable:true,
					buttons:[{
						text:"提交",
						iconCls:"fa fa-save",
						formBind:true,
						handler:function(){
							var win=this.up('form'),form = win.getForm();
				            if (form.isValid()) {
				                form.submit({
				                    success: function(form, action) {
				                    	Ext.toast("更新成功",'提示', 't');
				                    	me.refreshGrid();
				                    	win.hide();
				                    	
				                    },
				                    failure: function(form, action) {
				                    	Ext.toast(action.result.msg,'提示', 't');
				                    	me.refreshGrid();
				                    }
				                });
				            }	
						}
					},{
						text:"取消",
						iconCls:"fa fa-remove",
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			win.loadRecord(sel);
			win.show();
			
		},
		refreshGrid:function(){
			this.store.reload();
		},
		initSearchForm:function(region){
			var me=this,searchItems=FormFieldUtil.getSearchFormFields(me["mainMetaId"],me["metaData"],me.searchFields),
			formConfig={
					xtype:'form',
					layout:"hbox",
					split:true,
					scrollable:true,
					region:region,
					height:80,
					minHeight:50,
					width:'auto',
					bodyPadding:15,
					items:searchItems
			};
			searchItems.push({
				margin:'0 5 0 5',
				iconCls:"fa fa-search",
				xtype:'button',
				text:"搜索",
				handler:function(){
					var params=this.up('form').getValues();
					var proxy = me.store.getProxy(),
			       extraParams= proxy.extraParams;
					
					Ext.iterate(params,function(k,v,o){
						extraParams["filter."+k]=v||"";
					});
					var pagingtoolbar=me.getComponent(me["gridId"]).getComponent(me.pagingtoolbarId);
					pagingtoolbar.moveFirst();
				}
			});
			searchItems.push({
				margin:'0 5 0 5',
				xtype:'button',
				iconCls:'fa fa-refresh',
				text:"重置",
				handler:function(){
					this.up('form').reset();
					var params=this.up('form').getValues();
					var proxy = me.store.getProxy(),
				       extraParams= proxy.extraParams;
					Ext.iterate(params,function(k,v,o){
						extraParams["filter."+k]="";
					});
						var pagingtoolbar=me.getComponent(me["gridId"]).getComponent(me.pagingtoolbarId);
						pagingtoolbar.moveFirst();
				}
			});
			return formConfig;
		},
		initDataGrid:function(region){
			var me=this;
			
			this.initGridStore();
			this.initTBar();
			if(me.showColumns){
				Ext.iterate(me.columns,function(col,i){
					var name=col["dataIndex"];
					var exist=Ext.Array.contains(me.showColumns,name);
					col["hidden"]=!exist;
				});
			}
			
			var me=this,grid=this.gridPanel={
				xtype:"grid",
				tbar:me.tbar,
				minHeight:300,
				width:'auto',
				itemId:me.gridId,
				region:region,
				split:true,
				viewConfig: {
			        trackOver: false,
			        stripeRows: false,
			        enableTextSelection:true
			    },
			    store:me.store,
			    columns:me.columns,
				height:'auto',
				bbar: {
			        xtype: 'pagingtoolbar',
			        itemId:me.pagingtoolbarId,
			        displayInfo: true,
			        displayMsg: ' {0} - {1} 总数： {2}',
			        emptyMsg: "无数据",
			        store:me.store
			    },
			    listeners:{
			    	'itemdblclick':function( view, record, item, index, e, eOpts ) {
						me.showEditWin();
					}
			    }
			};
			return grid;
		}
	});
